<template>
	<a-modal title="添加物料" width="70%" :maskClosable="false" destoryOnClose :visible="visible"
		:confirmLoading="confirmLoading" @ok="handleSubmit" @cancel="handleCancel">
		<a-spin :spinning="confirmLoading">
			<div style="display: flex;align-items: center;margin: 5px 2px;">
				<div v-for="(item, index) in typeList" :key="index" class="type_item"
					:class="{ 'active_typeitem': currentTypeValue == item.id }" @click="typeClick(item)">
					{{ item.name }}
				</div>
			</div>
			<a-form>
				<a-row>
					<div v-if="!['1', '2'].includes(currentTypeValue)">
						<a-col :span="8">
							<a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
								<a-input placeholder="请输入 名称" v-model="queryParam.materialName" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="料号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
								<a-input placeholder="请输入 料号" v-model="queryParam.materialCode" />
							</a-form-item>
						</a-col>
					</div>
					<div v-else>
						<a-col :span="8">
							<a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
								<a-input placeholder="请输入 名称" v-model="queryParam.bomName" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="bom编码" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
								<a-input placeholder="请输入 bom编码" v-model="queryParam.bomCode" />
							</a-form-item>
						</a-col>
					</div>
					<a-col :span="8">
						<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-button type="primary" @click="handleQuery">
								搜索
							</a-button>
							<a-button style="margin-left: 20px;" @click="handleReset">
								重置
							</a-button>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
			<div v-if="!['1', '2'].includes(currentTypeValue)">
				<s-table ref="table" :scroll="{ x: 1400, y: 500 }" size="default" :columns="columns" :data="loadData"
					:alert="true" :rowKey="(record) => record.materialId"
					:rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
					<!-- <span slot="image" slot-scope="text, record">
						<image-preview :images="text" />
					</span> -->
					<span slot="image" slot-scope="text,record">
						<image-preview1 :images="text" :imageUrl="record.imageUrl" />
					</span>
					<span slot="actionMaterial" slot-scope="text, record">
						<template>
							<a @click="checkRow(record, 'null')">选择</a>
						</template>
					</span>
				</s-table>
			</div>
			<div v-else>
				<s-table ref="table1" :scroll="{ x: 1400, y: 500 }" size="default" :columns="columns" :data="loadData"
					:alert="false" :rowKey="(record) => record.bomId"
					:rowSelection="{ selectedRowKeys: selectedBomKeys, onChange: onSelectChangeBom }">
					<!-- <span slot="image" slot-scope="text, record">
						<image-preview :images="text" />
					</span> -->
					<span slot="image" slot-scope="text,record">
						<image-preview1 :images="text" :imageUrl="record.imageUrl" />
					</span>
					<span slot="action" slot-scope="text, record">
						<template>
							<a @click="checkRow(record, 'bom')">选择</a>
						</template>
					</span>
				</s-table>
			</div>
		</a-spin>
		<a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
			<image-preview :images="previewImage" :width="'100%'" :height="'100%'" />
		</a-modal>
	</a-modal>
</template>

<script>
import { STable } from '@/components'
import ImagePreview from '@/components/pbUpload/ImagePreview.vue'

import { del, page } from '@/api/modular/main/emsmaterial/emsMaterialManage';
import { page as BOM } from '@/api/modular/main/emsbom/emsBomManage';
import { listFull as emsBomMaterialListFull } from '@/api/modular/main/emsbommaterial/emsBomMaterialManage'

import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'


export default {
	components: {
		STable,
		ImagePreview
	},
	data() {
		return {
			labelCol: {
				xs: { span: 4 },
			},
			wrapperCol: {
				xs: { span: 15 },
			},
			labelColBlock: {
				xs: { span: 24 },
				sm: { span: 4 }
			},
			wrapperColBlock: {
				xs: { span: 24 },
				sm: { span: 18 }
			},
			queryParam: {},
			loadData: null,
			disabled: false,
			visible: false,
			confirmLoading: false,
			form: this.$form.createForm(this),
			loading: false,
			isPackaging: false,
			needDeleteFileUid: null,
			previewVisible: false,
			previewImage: '',
			fileList: [],
			orgIdStorehouse: null,
			sysOrgs: [],
			materialType: '',
			orgTree: [],
			// suppliers: [],
			danweiList: [],
			typeList: [
				this.$businessEnum.MATERIAL_TYPE_ENUM.material,
				this.$businessEnum.MATERIAL_TYPE_ENUM.cable,
				this.$businessEnum.MATERIAL_TYPE_ENUM.customized,

				//this.$businessEnum.MATERIAL_TYPE_ENUM.packing,
				{
					id: '1',
					name: '基础BOM'
				},
				{
					id: '2',
					name: '组合BOM'
				}
			],
			currentTypeValue: null,
			columns: [],
			selectedRowKeys: [],
			selectedRows: [],
			selectedBomKeys: [],
			selectedBomRows: [],
		}
	},
	computed: {
		token() {
			return Vue.ls.get(ACCESS_TOKEN)
		},
	},
	methods: {
		init(addOrEdit, record) {
			this.visible = true;
			console.log("addOrEdit", addOrEdit);
			console.log("record", record);

			this.currentTypeValue = this.typeList[0].id;
			let that = this;
			this.loadData = parameter => {
				that.queryParam = {
					...that.queryParam,
					materialType: that.currentTypeValue,
				}
				console.log(that.queryParam);

				return page(Object.assign(parameter, that.queryParam)).then(res => {
					return res.data
				})
			}

			that.columns = [
				{
					title: '序号', width: '80px',
					align: 'center',
					customRender: (text, record, index) => `${index + 1}`,
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '物料名称',
					dataIndex: 'materialName'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber'
				},
				{
					title: '图片',
					dataIndex: 'image',
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '库存',
					dataIndex: 'inventoryNumber'
				},
				{
					title: '供应商',
					dataIndex: 'orgIdSupplierName'
				},
				{
					title: '操作',
					width: '100px',
					dataIndex: 'actionMaterial',
					fixed: 'right',
					scopedSlots: { customRender: 'actionMaterial' }
				}
			];
			that.$nextTick(() => {
				that.$refs.table.refresh();
			})
			setTimeout(() => {
				console.log("record", record);
				this.selectedRowKeys = record.map(val => val.materialId);
				this.$refs.table.updateSelect(this.selectedRowKeys)
			}, 200);

			// if (addOrEdit) {

			// } else {
			// 	setTimeout(() => {
			// 		console.log("record", record);
			// 		this.selectedRowKeys = record.map(val => val.materialId);
			// 		this.$refs.table.updateSelect(this.selectedRowKeys)
			// 	}, 200);
			// }
		},
		imageURLFormat(text) {
			return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys;
			this.selectedRows = selectedRows;
			console.log("this.selectedRowKeys", selectedRowKeys);
			console.log("this.selectedRows", selectedRows);
		},
		onSelectChangeBom(selectedRowKeys, selectedRows) {
			// if (this.selectedBomKeys.length >= 1) {
			// 	this.$message.error('暂不支持多选BOM添加');
			// 	this.selectedBomKeys.splice(0, this.selectedBomKeys.length - 1);
			// 	this.selectedBomRows.splice(0, this.selectedBomRows.length - 1);
			// 	return
			// }
			this.selectedBomKeys = selectedRowKeys;
			this.selectedBomRows = selectedRows;
			console.log("this.selectedBomKeys", selectedRowKeys);
			console.log("this.selectedBomRows", selectedRows);
		},
		/**
		 * 行 选择操作
		 * @param record 
		 * @param type 
		 */
		checkRow(record, type) {
			if (type != 'bom') {
				if (this.selectedRowKeys.includes(record.materialId)) {
					return;
				} else {
					this.selectedRowKeys.push(record.materialId);
					this.selectedRows.push(record);
				}
				this.$refs.table.updateSelect(this.selectedRowKeys)
				console.log("this.selectedRowKeys", this.selectedRowKeys);
				console.log("this.selectedRows", this.selectedRows);
			} else {
				if (this.selectedBomKeys.includes(record.bomId)) {
					return
				} else {
					if (this.selectedBomKeys.length >= 1) {
						this.$message.error('暂不支持多选BOM添加')
						return
					}
					this.selectedBomKeys.push(record.bomId);
					this.selectedBomRows.push(record);
				}
				this.$refs.table1.updateSelect(this.selectedRowKeys)
			}
		},
		/**
		 * 类型切换
		 * @param item 
		 */
		typeClick(item, isclearParam = true) {
			let that = this;
			that.currentTypeValue = item.id;
			if (isclearParam) {
				that.queryParam = {};
			}
			if (this.currentTypeValue == 1 || this.currentTypeValue == 2) {
				that.queryParam = {
					...that.queryParam,
					bomType: that.currentTypeValue
				}
				this.columns = [       // 表头
					{
						title: '序号', width: '80px',
						align: 'center',
						customRender: (text, record, index) => `${index + 1}`,
					},
					{
						title: 'BOM名称',
						dataIndex: 'bomName',
						ellipsis: true
					},
					{
						title: 'BOM编码',
						dataIndex: 'bomCode',
						ellipsis: true
					},
					{
						title: '图片',
						dataIndex: 'image',
						// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
						scopedSlots: { customRender: 'image' }
					},
					{
						title: '更新时间',
						dataIndex: 'createTime',
					},
					{
						title: '分类',
						dataIndex: 'bomClassName'
					},
					{
						title: '成本',
						dataIndex: 'cost'
					},
					{
						title: '操作',
						dataIndex: 'action',
						width: '200px',
						scopedSlots: { customRender: 'action' }
					}
				];
				this.loadData = (parameter) => {
					return BOM(Object.assign(parameter, that.queryParam)).then(res => {
						return res.data
					})
				}
				that.$nextTick(() => {
					that.$refs.table1.refresh();
				})
			} else {
				this.columns = [
					{
						title: '序号', width: '80px',
						align: 'center',
						customRender: (text, record, index) => `${index + 1}`,
					},
					{
						title: '料号',
						dataIndex: 'materialCode'
					},
					{
						title: '物料名称',
						dataIndex: 'materialName'
					},
					{
						title: '规格',
						dataIndex: 'materialModelNumber'
					},
					{
						title: '图片',
						dataIndex: 'image',
						scopedSlots: { customRender: 'image' }
					},
					{
						title: '库存',
						dataIndex: 'inventoryNumber'
					},
					{
						title: '供应商',
						dataIndex: 'orgIdSupplierName'
					},
					{
						title: '操作',
						width: '100px',
						dataIndex: 'actionMaterial',
						fixed: 'right',
						scopedSlots: { customRender: 'actionMaterial' }
					}
				];
				that.queryParam = {
					...that.queryParam,
					materialType: that.currentTypeValue
				}
				this.loadData = parameter => {
					return page(Object.assign(parameter, that.queryParam)).then(res => {
						return res.data
					})
				}
				that.$nextTick(() => {
					that.$refs.table.refresh();
				})
			}

		},
		/**
		 * 搜索
		 */
		handleQuery() {
			this.typeClick({
				id: this.currentTypeValue,
			}, false)
		},
		/**
		 * 重置
		 */
		handleReset() {
			this.queryParam = {};
			this.typeClick({
				id: this.currentTypeValue,
			})
		},
		// 打开弹框时候生成一个单号
		createOrderNumber() {
			var d = new Date()
			var year = d.getFullYear()
			var month = d.getMonth()
			month = month + 1 > 12 ? 1 : month + 1
			month = month > 9 ? month : "0" + month.toString()
			var day = d.getDate()
			day = day > 9 ? day : "0" + day.toString()
			var hour = d.getHours()
			hour = hour > 9 ? hour : "0" + hour.toString()
			var minute = d.getMinutes()
			minute = minute > 9 ? minute : "0" + minute.toString()
			var second = d.getSeconds()
			second = second > 9 ? second : "0" + second.toString()

			let num = parseInt(Math.random() * 100000).toString()
			// 如果随机数长度不够5位,则在后面补0,够5位为止
			for (let i = num.length; i < 5; i++) {
				num += '0'
			}

			// let header = this.type==this.ORDER_TYPE_ENUM.inOrder.id?'WDRK': this.type==this.ORDER_TYPE_ENUM.outOrder.id?'WDCK':''

			let scOrderNo = 'LH' + year + month + day + hour + minute + second + num

			this.form.setFieldsValue({ materialCode: scOrderNo })
		},
		async handleSubmit() {
			let selectedRowKeys = [];
			selectedRowKeys = this.selectedRowKeys;
			if (this.selectedBomKeys.length > 1) {
				this.$message.error('暂不支持多选BOM添加')
				return
			}
			let bomList = [];
			if (this.selectedBomKeys.length != 0) {
				let bomIdSource = this.selectedBomKeys[0];
				let { data } = await emsBomMaterialListFull({ bomIdSource });
				data.forEach(val => {
					if (!selectedRowKeys.includes(val.materialId)) {
						selectedRowKeys.push(val.materialId)
					}
				})
				bomList = data;
			}
			let newSelectedRowsId = this.selectedRows.map(val => val.materialId);
			console.log(newSelectedRowsId);
			let newBomList = [];
			bomList.forEach(val => {
				if (!newSelectedRowsId.includes(val.materialId)) {
					newBomList.push(val)
				}
			});
			let selectedRows = this.selectedRows.concat(newBomList);

			this.$emit("ok", {
				selectedRowKeys: selectedRowKeys,
				selectedRows: selectedRows
			})
			this.selectedBomKeys = [];
			this.selectedBomRows = [];
			this.selectedRowKeys = [];
			this.selectedRows = [];
			this.visible = false;
		},
		handleCancel() {
			this.form.resetFields();
			this.fileList = []
			this.visible = false
		},

	}
}
</script>
<style lang="less">
.type_item {
	border: 1px solid #ccc;
	border-radius: 5px;
	padding: 5px 15px;
	margin: 5px;
	cursor: pointer;
	font-weight: bold;
}

.active_typeitem {
	background-color: #409EFF;
	color: #fff;
}
</style>